package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.OvershootInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.blankj.utilcode.util.TimeUtils;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.yxq.mdt.app.BuildConfig;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.constant.Constant;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.glide.GlideHelper;
import com.yxq.mdt.app.modules.bottomsheet.GiveListBottomSheetDialogFragment;
import com.yxq.mdt.app.modules.chat.ui.ChatActivity;
import com.yxq.mdt.app.modules.personal.bean.MyPersonalBean;
import com.yxq.mdt.app.modules.personal.ui.activity.MainPersonalBrowsingHistoryAc;
import com.yxq.mdt.app.modules.personal.ui.activity.MainPersonalEditData;
import com.yxq.mdt.app.modules.personal.ui.activity.RechargeActivity;
import com.yxq.mdt.app.modules.picturebrowse.ui.PictureActivity;
import com.yxq.mdt.app.modules.socialcontact.adapter.ExamplePagerAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.GivePresentBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialPersonalHomepageBean;
import com.yxq.mdt.app.modules.socialcontact.bean.SocialPersonalMyHomepageBean;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.presenter.MainSocialPersonalHomePresenter;
import com.yxq.mdt.app.modules.socialcontact.presenter.mainSocialPersonalHomeContract;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.SocialMaterialFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.SocialPhotoFragment;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.SocialStateFragment;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.DisplayUtil;
import com.yxq.mdt.app.utils.MediaPlayerHelper;
import com.yxq.mdt.app.utils.ScaleTransitionPagerTitleView;
import com.yxq.mdt.app.widgets.CircleImageView;
import com.yxq.mdt.app.widgets.NonSwipeableViewPager;

import net.lucode.hackware.magicindicator.FragmentContainerHelper;
import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jzvd.Jzvd;


/**
 * @author L
 * @time
 * @describe 个人主页
 */
public class SocialPersonalHomepageAc extends BaseActivity<MainSocialPersonalHomePresenter> implements mainSocialPersonalHomeContract.View {
    @BindView(R.id.item_number_tv)
    TextView itemNumberTv;
    @BindView(R.id.video_magic_indicator)
    MagicIndicator videoMagicIndicator;
    private static final String[] CHANNELS = new String[]{"资料", "动态", "相册"};
    @BindView(R.id.video_view_pager)
    NonSwipeableViewPager videoViewPager;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.personal_home_banner)
    ConvenientBanner personalHomeBanner;
    @BindView(R.id.personal_home_text)
    TextView personalHomeText;
    @BindView(R.id.personal_home_sex)
    ImageView personalHomeSex;
    @BindView(R.id.personal_home_vice)
    ImageView personalHomeVice;
    @BindView(R.id.personal_home_autograph)
    TextView personalHomeAutograph;
    @BindView(R.id.personal_home_fans)
    TextView personalHomeFans;
    @BindView(R.id.personal_home_follow)
    TextView personalHomeFollow;
    @BindView(R.id.look_me_img)
    CircleImageView lookMeImg;
    @BindView(R.id.look_me_relativeLayout)
    RelativeLayout lookMe;
    @BindView(R.id.item_number_lint)
    LinearLayout itemNumberLint;
    @BindView(R.id.call_phone)
    LinearLayout callPhone;
    @BindView(R.id.social_give_present_phone)
    TextView socialGivePresentPhone;
    @BindView(R.id.call_phone_lint)
    LinearLayout callPhoneLint;
    @BindView(R.id.call_video)
    LinearLayout callVideo;
    @BindView(R.id.social_give_present)
    TextView socialGivePresent;
    @BindView(R.id.social_give_present_lint)
    LinearLayout socialGivePresentLint;
    @BindView(R.id.call_video_lint)
    LinearLayout callVideoLint;
    @BindView(R.id.social_give_present_new)
    TextView socialGivePresentNew;
    @BindView(R.id.social_give_present_new_lint)
    LinearLayout socialGivePresentNewLint;
    @BindView(R.id.social_edit_tv)
    TextView socialEditTv;
    @BindView(R.id.social_edit_lint)
    LinearLayout socialEditLint;
    @BindView(R.id.call_vice_chat)
    TextView callViceChat;
    @BindView(R.id.call_video_chat)
    TextView callVideoChat;
    @BindView(R.id.call_give_chat)
    TextView callGiveChat;
    @BindView(R.id.personal_home_time)
    TextView personalHomeTime;
    private List<String> mDataList = Arrays.asList(CHANNELS);
    private List<Fragment> mFragments = new ArrayList<Fragment>();
    private List<SocialPersonalHomepageBean.IntroductionImgFileBean> socialPersonalHomepageBeans;
    private ExamplePagerAdapter mExamplePagerAdapter;
    private FragmentContainerHelper mFragmentContainerHelper = new FragmentContainerHelper();
    String userId = "", name = "";
    MyPersonalBean myPersonalBean;
    CountDownTimer countDownTimer;
    GiveListBottomSheetDialogFragment giveListBottomSheetDialogFragment;
    private List<GivePresentBean.DataBean.ListBean> givePresentBeans;
    public boolean isVoiceStart = false;
    SocialMaterialFragment socialMaterialFragment;

    @Override
    public int getLayoutId() {
        return R.layout.activity_social_personal_homepage;
    }

    @SuppressLint("Range")
    @Override
    public void initView() {
        if (getIntent().getStringExtra("userId") != null || getIntent().getStringExtra("name") != null) {
            userId = getIntent().getStringExtra("userId");
            name = getIntent().getStringExtra("name");
        } else {
            personalHomeText.setText(name);
            text.setText(name);
        }

        givePresentBeans = new ArrayList<>();
        socialPersonalHomepageBeans = new ArrayList<>();
        int screenWidth = DisplayUtil.getScreenRelatedInformation(mActivity);
        initFragments();
        mExamplePagerAdapter = new ExamplePagerAdapter(getSupportFragmentManager(), mFragments, mDataList);
        videoViewPager.setAdapter(mExamplePagerAdapter);
        initMagicIndicator4();
        final int alphaMaxOffset = dpToPx(150);
        mFragmentContainerHelper.handlePageSelected(0, false);
        toolbar.getBackground().setAlpha(0);
        appBar.addOnOffsetChangedListener((appBarLayout, verticalOffset) -> {
            // 设置 toolbar 背景
            if (verticalOffset > -alphaMaxOffset) {
                toolbar.getBackground().setAlpha(255 * -verticalOffset / alphaMaxOffset);
                text.setTextColor(getResources().getColor(R.color.transparent));
                personalHomeFans.setVisibility(View.VISIBLE);
            } else {
                toolbar.getBackground().setAlpha(255);
                text.setTextColor(getResources().getColor(R.color.white));
                personalHomeFans.setVisibility(View.GONE);
            }
        });
        new Handler().postDelayed(() -> ImmersionBar.with(mActivity)
                .transparentStatusBar()  //透明状态栏
                .hideBar(BarHide.FLAG_HIDE_STATUS_BAR)//隐藏状态栏
                .init(), 50);

        toolbar.setNavigationOnClickListener(view -> finish());

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) personalHomeBanner.getLayoutParams();
        layoutParams.height = screenWidth;
        personalHomeBanner.setLayoutParams(layoutParams);

        lookMe.setOnClickListener(view -> {
            Intent it = new Intent(mActivity, MainPersonalBrowsingHistoryAc.class);
            startActivity(it);
        });
        lookMeImg.setOnClickListener(view -> {
            Intent it = new Intent(mActivity, MainPersonalBrowsingHistoryAc.class);
            startActivity(it);
        });
    }

    private void initMagicIndicator4() {
        CommonNavigator commonNavigator = new CommonNavigator(mActivity);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); //使用自定义
                simplePagerTitleView.setNormalColor(Color.BLACK);
                simplePagerTitleView.setSelectedColor(Color.BLACK);
                simplePagerTitleView.setText(mDataList.get(index));
                simplePagerTitleView.setTextSize(20);
                simplePagerTitleView.setOnClickListener(v -> {
                    videoViewPager.setCurrentItem(index);
//                    switchPages(index);
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator linePagerIndicator = new LinePagerIndicator(context);
                linePagerIndicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                linePagerIndicator.setLineWidth(UIUtil.dip2px(context, 40));
                linePagerIndicator.setLineHeight(UIUtil.dip2px(context, 2));
                linePagerIndicator.setColors(Color.parseColor("#FD4343"));
                return linePagerIndicator;
            }
        });
        videoMagicIndicator.setNavigator(commonNavigator);
        LinearLayout titleContainer = commonNavigator.getTitleContainer(); // must after setNavigator
        titleContainer.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
        titleContainer.setDividerDrawable(new ColorDrawable() {
            @Override
            public int getIntrinsicWidth() {
                return UIUtil.dip2px(mActivity, 0);
            }
        });
        final FragmentContainerHelper fragmentContainerHelper = new FragmentContainerHelper(videoMagicIndicator);
        fragmentContainerHelper.setInterpolator(new OvershootInterpolator(0.1f));
        fragmentContainerHelper.setDuration(0);
        videoViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                if (position != 1) {
                    Jzvd.goOnPlayOnPause();
                }
                fragmentContainerHelper.handlePageSelected(position);
            }
        });
        videoViewPager.setOffscreenPageLimit(3);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter = new MainSocialPersonalHomePresenter(this, new MainSocialContactModel());
        mPresenter.getGaUserExtVoById(userId);
        mPresenter.getSelectByGsPresentPageList();
    }

    //初始化fragment addFragment
    private void initFragments() {

        //资料
        socialMaterialFragment = new SocialMaterialFragment();
        Bundle bundle = new Bundle();
        bundle.putString("userId", userId);
        socialMaterialFragment.setArguments(bundle);
        mFragments.add(socialMaterialFragment);
        //动态
        SocialStateFragment socialStateFragment = new SocialStateFragment();
        Bundle bundl5 = new Bundle();
        bundl5.putString("userId", userId);
        socialStateFragment.setArguments(bundl5);
        mFragments.add(socialStateFragment);
        //相册
        SocialPhotoFragment socialPhotoFragment = new SocialPhotoFragment();
        Bundle bundle2 = new Bundle();
        bundle2.putString("userId", userId);
        socialPhotoFragment.setArguments(bundle2);
        mFragments.add(socialPhotoFragment);
//                case 3:
//                    //作品
//                    SocialWorksFragment socialWorksFragment = new SocialWorksFragment();
//                    Bundle bundle3 = new Bundle();
//                    bundle3.putString(SocialWorksFragment.EXTRA_TEXT, CHANNELS[i]);
//                    socialWorksFragment.setArguments(bundle3);
//                    mFragments.add(socialWorksFragment);
//                    break;
    }


    protected void initToolBar() {
        try {
            if (toolbar != null) {
                // 沉浸模式
                int statusBarHeight = getStatusBarHeight();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    openAndroidLStyle();

                    toolbar.setPadding(0, statusBarHeight, 0, 0);
                    toolbar.getLayoutParams().height = dpToPx(46) + statusBarHeight;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启沉浸式模式支持
     */
    public void openAndroidLStyle() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 获取状态栏高度
     */
    public int getStatusBarHeight() {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            return getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * dp转换为px
     */
    public static int dpToPx(float dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density + 0.5f);
    }

    @Override
    public void onBackPressed() {
        if (Jzvd.backPress()) {
            return;
        }
        super.onBackPressed();
    }


//    @Override
//    protected void onPause() {
//        super.onPause();
//        Jzvd.releaseAllVideos();
//    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onLoadMyGaUserExtVoByIdSuccess(SocialPersonalMyHomepageBean socialPersonalMyHomepageBean) {

    }

    @Override
    public void onLoadMyGaUserExtVoByIdFailed() {

    }

    @Override
    public void onLoadGaUserExtVoByIdSuccess(SocialPersonalHomepageBean socialPersonalHomepageBean) {
        if (socialPersonalHomepageBean == null) {
            return;
        }
        //getUser(socialPersonalHomepageBean);
    }

    @Override
    public void onLoadGaUserExtVoByIdFailed() {

    }

    @Override
    public void onLoadRelationSuccess(String s) {
        mPresenter.getGaUserExtVoById(userId);
    }

    @Override
    public void onLoadRelationFailed() {

    }

    @Override
    public void onLoadSelectByGsPresentPageListSuccess(GivePresentBean givePresentBean) {
        if (givePresentBean != null) {
            givePresentBeans.addAll(givePresentBean.getData().getList());
        }
    }

    @Override
    public void onLoadSelectByGsPresentPageListFailed() {

    }

    SocialPersonalHomepageBean mSocialPersonalHomepageBean;

    private void getUser(SocialPersonalHomepageBean socialPersonalHomepageBean) {
        mSocialPersonalHomepageBean = socialPersonalHomepageBean;
        if (socialPersonalHomepageBean.getIntroductionImgFile().size() != 1) {
            personalHomeBanner.setPageIndicator(new int[]{R.drawable.shape_banner_selector_unchecked, R.drawable.shape_banner_selector_checked});
        }
        Hawk.put(SPKey.SP_KEY_USER_PERFECTTATIO_NUMBER, socialPersonalHomepageBean.getPerfectRatio());
        //个性签名
        if (!TextUtils.isEmpty(socialPersonalHomepageBean.getGeneration())) {
            personalHomeAutograph.setText(socialPersonalHomepageBean.getGeneration());
        } else {
            personalHomeAutograph.setText("");
        }
        //昵称
        text.setText(socialPersonalHomepageBean.getGsName());
        personalHomeText.setText(socialPersonalHomepageBean.getGsName());
        //粉丝
        personalHomeFans.setText(socialPersonalHomepageBean.getRelationFs() + "粉丝");
        //性别图标
        if (socialPersonalHomepageBean.getSex() == 1) {
            personalHomeSex.setImageResource(R.mipmap.xb_nan);
        } else {
            personalHomeSex.setImageResource(R.mipmap.xb_nv);
        }
        if (socialPersonalHomepageBean.getIntroductionAudioFile() != null && socialPersonalHomepageBean.getIntroductionAudioFile().size() > 0) {
            itemNumberLint.setVisibility(View.VISIBLE);
        } else {
            itemNumberLint.setVisibility(View.GONE);
        }

        initGoodsImages(socialPersonalHomepageBean);
        if (socialPersonalHomepageBean.getIntroductionAudioFile().size() > 0) {
            if (socialPersonalHomepageBean.getIntroductionAudioFile().get(0).getFileLength() < 1000) {
                itemNumberTv.setText(socialPersonalHomepageBean.getIntroductionAudioFile().get(0).getFileLength() + "″");
            } else {
                itemNumberTv.setText(socialPersonalHomepageBean.getIntroductionAudioFile().get(0).getFileLength() / 1000 + "″");
            }
        }

        socialPersonalHomepageBeans.addAll(socialPersonalHomepageBean.getIntroductionImgFile());

        if (socialPersonalHomepageBean.getIntroductionImgFile() == null || (socialPersonalHomepageBean.getIntroductionImgFile() != null && socialPersonalHomepageBean.getIntroductionImgFile().size() == 0)) {
            personalHomeBanner.setBackgroundResource(R.mipmap.placeholder_noraml);
        }
        myPersonalBean = Hawk.get(SPKey.SP_KEY_USER_MY_INFO);
        if ((myPersonalBean.getUserId() + "").equals(userId)) {
            lookMe.setVisibility(View.VISIBLE);
            personalHomeFollow.setVisibility(View.GONE);
        } else {
            lookMe.setVisibility(View.GONE);
            personalHomeFollow.setVisibility(View.VISIBLE);
        }
        if (socialPersonalHomepageBean.getMyViewUserList() != null && socialPersonalHomepageBean.getMyViewUserList().size() != 0 && socialPersonalHomepageBean.getMyViewUserList().get(0) != null) {
            GlideHelper.setLoadImage(mActivity, socialPersonalHomepageBean.getMyViewUserList().get(0).getHeadimg(), R.mipmap.head_icon, lookMeImg);
            personalHomeTime.setText(TimeUtils.getFriendlyTimeSpanByNow(socialPersonalHomepageBean.getMyViewUserList().get(0).getOperDate(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")) + "访问");
        } else {
            lookMe.setVisibility(View.GONE);
        }
        itemNumberLint.setOnClickListener(view -> {
            if (socialPersonalHomepageBean.getIntroductionAudioFile().get(0).getFilePath() != null || socialPersonalHomepageBean.getIntroductionAudioFile() != null) {

                if (isVoiceStart) {
                    isVoiceStart = false;
                    MediaPlayerHelper.realese();
                    countDownTimer.onFinish();
                } else {
                    isVoiceStart = true;
                    MediaPlayerHelper.playSound(socialPersonalHomepageBean.getIntroductionAudioFile().get(0).getFilePath(), mediaPlayer -> isVoiceStart = false);
                    getTime(socialPersonalHomepageBean.getIntroductionAudioFile().get(0).getFileLength() / 1000 + "", itemNumberTv);
                    countDownTimer.start();
                }


            }
        });
        personalHomeFollow.setOnClickListener(view -> {
            if (socialPersonalHomepageBean.getRelation() == 0) {
                MainSocialContactModel.setInterestRelation(socialPersonalHomepageBean.getUserId() + "", 1, 1, new ApiModel.CommonCallback<String>() {
                    @Override
                    public void onSuccess(String s) {
                        showCenterToast("关注成功");
                        socialPersonalHomepageBean.setRelation(1);
                        personalHomeFollow.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(String errMsg) {
                        showCenterToast("关注失败");
                    }
                });


            }

        });
        if (socialPersonalHomepageBean.getRelation() == 0) {
            personalHomeFollow.setText("关注");
        } else {
            personalHomeFollow.setVisibility(View.GONE);
        }
        if (!(myPersonalBean.getUserId() + "").equals(userId)) {
            MainSocialContactModel.setSaveViewParameter("1", socialPersonalHomepageBean.getId() + "", "4", new ApiModel.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {

                }

                @Override
                public void onError(String errMsg) {
                }
            });
        }
        if ((myPersonalBean.getUserId() + "").equals(userId)) {
            //登录用户首页 显示编辑个人资料按钮
            callVideoLint.setVisibility(View.GONE);
            callPhoneLint.setVisibility(View.GONE);
            socialGivePresentNewLint.setVisibility(View.GONE);
            socialEditLint.setVisibility(View.VISIBLE);
        } else if (socialPersonalHomepageBean.getSoundsVideoStatus() == 0 || String.valueOf(socialPersonalHomepageBean.getSoundsVideoStatus()) != null) {
            callVideoLint.setVisibility(View.GONE);
            callPhoneLint.setVisibility(View.GONE);
            socialEditLint.setVisibility(View.GONE);
            socialGivePresentNewLint.setVisibility(View.VISIBLE);
            if (socialPersonalHomepageBean.getSoundsVideoStatus() == 2) {
                socialGivePresentNewLint.setVisibility(View.GONE);
                callVideoLint.setVisibility(View.VISIBLE);
                callPhoneLint.setVisibility(View.GONE);
                socialEditLint.setVisibility(View.GONE);
            } else if (socialPersonalHomepageBean.getSoundsVideoStatus() == 1) {
                socialGivePresentNewLint.setVisibility(View.GONE);
                callVideoLint.setVisibility(View.GONE);
                callPhoneLint.setVisibility(View.VISIBLE);
                socialEditLint.setVisibility(View.GONE);
            }
        }
        if (BuildConfig.DEBUG) {
//            findViewById(R.id.call_vice_chat_layout).setVisibility(View.VISIBLE);
//            findViewById(R.id.call_video_chat_layout).setVisibility(View.VISIBLE);
//            findViewById(R.id.call_give_chat_layout).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.call_vice_chat_layout).setVisibility(View.GONE);
            findViewById(R.id.call_video_chat_layout).setVisibility(View.GONE);
            findViewById(R.id.call_give_chat_layout).setVisibility(View.GONE);
        }
    }

    /**
     * 初始化个人主页轮播图
     *
     * @param socialPersonalHomepageBean
     */
    private void initGoodsImages(SocialPersonalHomepageBean socialPersonalHomepageBean) {
        name = socialPersonalHomepageBean.getGsName();


        personalHomeBanner.setPages(new CBViewHolderCreator() {
            @Override
            public Holder createHolder(View itemView) {

                return new ImageHolderView(itemView);
            }

            @Override
            public int getLayoutId() {
                return R.layout.layout_banner_item;
            }
        }, socialPersonalHomepageBean.getIntroductionImgFile());
        personalHomeBanner.startTurning();
        personalHomeBanner.setOnItemClickListener(position -> {
            //预览
            Intent intent = new Intent(mActivity, PictureActivity.class);
            intent.putExtra("position", position);
            ArrayList<String> images = new ArrayList<>();
            for (SocialPersonalHomepageBean.IntroductionImgFileBean photoImgFile : socialPersonalHomepageBean.getIntroductionImgFile()) {
                if (photoImgFile.getId() != -1) {
                    images.add(photoImgFile.getFilePath());
                }
            }
            intent.putExtra("images", images);
            startActivity(intent);
        });
    }


    /**
     * 图片轮转实现
     */
    class ImageHolderView extends Holder<SocialPersonalHomepageBean.IntroductionImgFileBean> {
        private ImageView imageView;

        public ImageHolderView(View itemView) {
            super(itemView);
        }

        @Override
        protected void initView(View itemView) {
            imageView = itemView.findViewById(R.id.banner_image);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        }

        @Override
        public void updateUI(SocialPersonalHomepageBean.IntroductionImgFileBean bean) {
            if (bean.getFilePath() == null) {
                GlideHelper.setLoadImage(mActivity, bean.getFilePath(), R.mipmap.placeholder_noraml, imageView);
            } else {
                GlideHelper.setLoadImage(mActivity, bean.getFilePath(), R.color.gray, imageView);
            }
        }

    }

    /**
     * @param playTime 开始时间
     * @param timeTv   获取显示秒数
     */
    private void getTime(String playTime, TextView timeTv) {
        countDownTimer = new CountDownTimer(Integer.parseInt(playTime) * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeTv.setText(millisUntilFinished / 1000 + "″");
            }

            @Override
            public void onFinish() {
                timeTv.setText(playTime + "″");
                countDownTimer.cancel();
            }
        };
    }

    @OnClick({R.id.social_give_present_phone_layout, R.id.social_give_present_lint, R.id.social_give_present_new_lint, R.id.social_edit_lint, R.id.call_phone, R.id.call_video, R.id.call_vice_chat_layout, R.id.call_video_chat_layout, R.id.call_give_chat_layout})
    public void onViewClicked(View view) {
        String YXQUserId = "yxq" + userId;
        switch (view.getId()) {
            case R.id.social_give_present_phone_layout:
            case R.id.social_give_present_lint:
            case R.id.social_give_present_new_lint:
                //送礼界面
                giveListBottomSheetDialogFragment = new GiveListBottomSheetDialogFragment(givePresentBeans, userId, name);
                giveListBottomSheetDialogFragment.show(getSupportFragmentManager(), "giveListBottomSheetDialogFragment");
                break;
            case R.id.social_edit_lint:
                Intent it = new Intent(mActivity, MainPersonalEditData.class);
                it.putExtra("userId", userId);
                mActivity.startActivity(it);
                break;
            case R.id.call_vice_chat_layout:
            case R.id.call_video_chat_layout:
            case R.id.call_give_chat_layout:
                //聊天
                startActivity(new Intent(mActivity, ChatActivity.class).putExtra("userId", YXQUserId));
                break;
            case R.id.call_phone:
                //语音
                if (Constant.getSocialUser().getMoney() < mSocialPersonalHomepageBean.getVoicePrice()) {

                    CostumerDialog dialog = new CostumerDialog.Builder(mActivity, R.style.custom_dialog_no_match)
                            .setContentView(R.layout.dialog_clear_cache_layout)
                            .setCancelable(true)
                            .create();

                    TextView tvTitle = dialog.findViewById(R.id.tv_title);

                    tvTitle.setText("余额不足");

                    TextView content = dialog.findViewById(R.id.tv_content);
                    content.setText("当前余额不足，充值后可继续送礼，是否去充值？");

                    //充值
                    TextView sure = dialog.findViewById(R.id.tv_sure);
                    sure.setText("充值");
                    sure.setOnClickListener(v -> {
                        Intent inten = new Intent(mActivity, RechargeActivity.class);
                        startActivity(inten);
                        dialog.dismiss();
                    });

                    //取消
                    TextView cancel = dialog.findViewById(R.id.tv_cancel);
                    cancel.setText("取消");
                    cancel.setOnClickListener(v -> {
                        dialog.dismiss();
                    });
                    dialog.show();
                    return;
                }
                Intent goToChat = new Intent(mActivity, VoiceInviteChatActivity.class);
                goToChat.putExtra("userId", YXQUserId);
                goToChat.putExtra("nickname", name);
                startActivity(goToChat);
                break;
            case R.id.call_video:
                //视频
                if (Constant.getSocialUser().getMoney() < mSocialPersonalHomepageBean.getVideoPrice()) {

                    CostumerDialog dialog = new CostumerDialog.Builder(mActivity, R.style.custom_dialog_no_match)
                            .setContentView(R.layout.dialog_clear_cache_layout)
                            .setCancelable(true)
                            .create();

                    TextView tvTitle = dialog.findViewById(R.id.tv_title);

                    tvTitle.setText("余额不足");

                    TextView content = dialog.findViewById(R.id.tv_content);
                    content.setText("当前余额不足，充值后可继续送礼，是否去充值？");

                    //充值
                    TextView sure = dialog.findViewById(R.id.tv_sure);
                    sure.setText("充值");
                    sure.setOnClickListener(v -> {
                        Intent inten = new Intent(mActivity, RechargeActivity.class);
                        startActivity(inten);
                        dialog.dismiss();
                    });

                    //取消
                    TextView cancel = dialog.findViewById(R.id.tv_cancel);
                    cancel.setText("取消");
                    cancel.setOnClickListener(v -> {
                        dialog.dismiss();
                    });
                    dialog.show();
                    return;
                }
                goToChat = new Intent(mActivity, VideoInviteChatActivity.class);
                goToChat.putExtra("userId", YXQUserId);
                goToChat.putExtra("nickname", name);
                startActivity(goToChat);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (Jzvd.backPress()) {
                return true;
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        MediaPlayerHelper.realese();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        Jzvd.releaseAllVideos();
        MediaPlayerHelper.realese();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MainSocialContactModel.getGaUserExtVoById(userId, new ApiModel.CommonCallback<SocialPersonalHomepageBean>() {
            @Override
            public void onSuccess(SocialPersonalHomepageBean socialPersonalHomepageBean) {
                getUser(socialPersonalHomepageBean);
                if(socialMaterialFragment!=null){
                    socialMaterialFragment.initData();
                }
            }

            @Override
            public void onError(String errMsg) {

            }
        });
    }
}
